package com.demo.prototype.deepClone;

import java.io.*;

public class DeepProtoType implements Serializable, Cloneable {

    private String className;
    private DeepCloneableTarget deepCloneableTarget;

    public String getClassName() {
        return className;
    }

    public void setClassName(String className) {
        this.className = className;
    }

    public DeepCloneableTarget getDeepCloneableTarget() {
        return deepCloneableTarget;
    }

    public void setDeepCloneableTarget(DeepCloneableTarget deepCloneableTarget) {
        this.deepCloneableTarget = deepCloneableTarget;
    }

    @Override
    public String toString() {
        return "DeepProtoType{" +
                "className='" + className + '\'' +
                ", deepCloneableTarget=" + deepCloneableTarget +
                '}';
    }

    // 方式一
    @Override
    protected Object clone() throws CloneNotSupportedException {
        DeepProtoType deep = (DeepProtoType) super.clone();

        deep.setDeepCloneableTarget((DeepCloneableTarget) deepCloneableTarget.clone());
        return deep;
    }

    // 方式二
    public DeepProtoType deepClone() throws IOException {
        ByteArrayOutputStream bos = null;
        ObjectOutputStream oos = null;
        ByteArrayInputStream bis = null;
        ObjectInputStream ois = null;

        try {
            // 序列化
            bos = new ByteArrayOutputStream();
            oos = new ObjectOutputStream(bos);
            oos.writeObject(this);

            // 反序列化
            bis = new ByteArrayInputStream(bos.toByteArray());
            ois = new ObjectInputStream(bis);
            DeepProtoType deepProtoType = (DeepProtoType) ois.readObject();

            return deepProtoType;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        } finally {
            bos.close();
            oos.close();
            bis.close();
            ois.close();
        }
    }
}
